<?php

namespace App\Jobs\Zhunya;

use App\Models\CacheModel\zl4\Zl4GoodTimeTag;
use App\Models\CacheModel\zl4\Zl4HoroscopeGoodTimeTemp;
use App\Models\CacheModel\zl4\Zl4HoroscopeReport;
use App\Tools\Horoscope;
use App\Tools\HoroscopeFortune;
use Log;
use AstroTools\cache\CacheManage;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class HoroscopeReportJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $jobData;

    /**
     * Create a new job instance.
     *
     * @param array $jobData
     */
    public function __construct(array $jobData)
    {
        $this->jobData = $jobData;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function calculate()
    {
      $jobData = $this->jobData;
       // $jobData = [
        //     'id' => 1  // 计算数据 ID     zl4_horoscope_report表ID
        // ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 2)
        {   // 失败两次 则删除
            $job->delete();
            return;
        }
        $host = Util::getEcsIp();

        $startTime = date('Y-m-d H:i:s');

        $HoroscopeReportModel = new Zl4HoroscopeReport();
        $reportInfo = $HoroscopeReportModel->where(['id' => $jobData['id']])->find();

        if ($reportInfo['type'] == 1)
        {
            $logInfo = '72格局判定';
        } else
        {
            $logInfo = '用神详解';
        }

        try
        {
            // 档案信息
            $recodeInfo = json_decode($reportInfo['recode_info'], true);

            $logInfo .= "计算 开始:{$startTime} host:{$host} uid:{$recodeInfo['uid']} rid:{$recodeInfo['id']} name:{$recodeInfo['name']}";

            $resData = [];
            // 接入计算逻辑
            switch ($reportInfo['type'])
            {
                case 1: // 72格局判定
                    [$y, $m, $d, $h, $i] = explode(',', date('Y,m,d,H,i'));
                    $instance = Horoscope::getInstance([
                        'recode' => $recodeInfo,
                        'time_start' => 23,
                        'time_type' => 0,
//                        'shensha' => 2,
                        'advance' => [
                            'year' => (int)$y,
                            'month' => (int)$m,
                            'day' => (int)$d,
                            'hour' => (int)$h,
                            'minute' => (int)$i,
                            'timezone' => 8,
                            'is_summer' => 0,
                        ]
                    ]);
                    $bazi = $instance->data['bazi'];
                    $resData = $instance->gejupanding($bazi);
                    break;
                case 2: // 用神详解
                    $goodYears = $reportInfo['good_years'] ? explode(',', $reportInfo['good_years']) : [];
                    $goodYears = array_map(function ($val)
                    {
                        return (int)$val;
                    }, $goodYears);
                    $badYears = $reportInfo['bad_years'] ? explode(',', $reportInfo['bad_years']) : [];
                    $badYears = array_map(function ($val)
                    {
                        return (int)$val;
                    }, $badYears);
                    $resData = HoroscopeFortune::getInstance()->setRecord($recodeInfo)->baziyongshen(['good_years' => $goodYears, 'bad_years' => $badYears]);
                    break;
            }
            $updateData = [
                'content' => json_encode($resData, JSON_UNESCAPED_UNICODE),
                'status' => 2,
                'end_time' => time()
            ];
            // 更新结果
            $reportDataUpdateState = $HoroscopeReportModel->UpdateData($jobData['id'], (int)$reportInfo['rid'], $updateData);
            // 更新 订单数据
            $orderDataUpdateState = (new \app\common\cachemodel\Orders())->UpdateData($reportInfo['order_num'], ['status' => 4], 4);
            if (!$reportDataUpdateState)
            {
                $logInfo .= ' error: 计算完成更新结果失败 结果数据:' . json_encode($resData, JSON_UNESCAPED_UNICODE);
            }
            if (!$orderDataUpdateState)
            {
                $logInfo .= ' error: 计算完成更新订单状态失败 订单号:' . $reportInfo['order_num'];
            }
            if ($reportDataUpdateState && $orderDataUpdateState)
            {
                $logInfo .= ' success:' . date('Y-m-d H:i:s');
            }
//            $host = Util::getEcsIp();
//            Log::write("八字 - 报告【用神详解｜72格局判定】计算完成 IP:{$host} jobData：" . json_encode($jobData, JSON_UNESCAPED_UNICODE) . ';计算结果:' . $updateData['content'], 'log');
        }
        catch (\Exception $e)
        {
            $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
//            Log::write('八字 - 报告【用神详解｜72格局判定】计算异常 jobData：' . json_encode($jobData, JSON_UNESCAPED_UNICODE) . ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine(), 'error');
            // 计算失败
            $extend = [
                'msg' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
            ];
            $HoroscopeReportModel->UpdateData($jobData['id'], $reportInfo['rid'], ['status' => 3, 'end_time' => time(), 'extend' => json_encode($extend, JSON_UNESCAPED_UNICODE)]);
        }

        $logInfo .= ' jobData:' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        Log::write($logInfo, 'log', true);

        $job->delete();
    }

    /**
     * 八字 - 吉日吉时 逻辑计算
     */
    public function goodTimeCalculate(Job $job, $jobData)
    {
        // $jobData = [
        //     'id' => 1  // 计算数据 ID     zl4_horoscope_good_time 表ID
        // ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 2)
        {   // 失败两次 则删除
            $job->delete();
            return;
        }

        $HoroscopeGoodTimeModel = new Zl4HoroscopeGoodTimeTemp();

        $HoroscopeGoodTimeInfo = $HoroscopeGoodTimeModel->where(['id' => $jobData['id']])->find();

        try
        {
            $tagInfo = (new Zl4GoodTimeTag())->getInfoById($HoroscopeGoodTimeInfo['tid']);
            // 档案信息
            $recodeInfo = json_decode($HoroscopeGoodTimeInfo['recode_info'], true);
            // 接入计算逻辑
            $option = [
                'tid' => $HoroscopeGoodTimeInfo['tid'],
                'recode' => $recodeInfo['recode1'],
                'start_time' => $HoroscopeGoodTimeInfo['start_date'],
                'end_time' => $HoroscopeGoodTimeInfo['end_date'] + 86400,
            ];
            $resData = HoroscopeFortune::getInstance()->setRecord($recodeInfo['recode1'])->setAdvance(date('Y-m-d', $HoroscopeGoodTimeInfo['start_date']))->bazizeri($option);
            if ($tagInfo['type'] === 2)
            {   // 双盘模式  计算第二档案信息
                $option = [
                    'tid' => $HoroscopeGoodTimeInfo['tid'],
                    'recode' => $recodeInfo['recode2'],
                    'start_time' => $HoroscopeGoodTimeInfo['start_date'],
                    'end_time' => $HoroscopeGoodTimeInfo['end_date'] + 86400,
                ];
                $resData2 = HoroscopeFortune::getInstance()->setRecord($recodeInfo['recode2'])->setAdvance(date('Y-m-d', $HoroscopeGoodTimeInfo['start_date']))->bazizeri($option);

                $jiri = array_intersect($resData['jiri'], $resData2['jiri']);

                $jishi = [];
                foreach ($resData['jishi'] as $date => $value)
                {
                    if (in_array($date, $jiri, true))
                    {
                        $jishi[$date] = $value;
                    }
                }

                $resData = [
                    'jiri' => $jiri,
                    'jishi' => $jishi
                ];
            }

            $dayNum = count($resData['jiri']);
            $extend = json_decode($HoroscopeGoodTimeInfo['extend'], true);
            if ($extend['unlocked_day_num'] > 0 && $extend['unlocked_days'])
            {
                foreach ($resData['jiri'] as $datum)
                {   // 如果 之前已解锁
                    $t = strtotime($datum);
                    if ($extend['unlocked_day_num'] === 1)
                    {
                        if ($t === $extend['unlocked_days'][0])
                        {
                            $dayNum--;
                        }
                    } else
                    {
                        if ($t >= $extend['unlocked_days'][0] && $t <= $extend['unlocked_days'][1])
                        {
                            $dayNum--;
                        }
                    }
                }
            }

            $updateData = [
                'content' => json_encode($resData, JSON_UNESCAPED_UNICODE),
                'day_num' => $dayNum, // 吉日天数
                'status' => 2,
                'end_time' => time()
            ];
            // 更新结果
            $HoroscopeGoodTimeModel->UpdateData($jobData['id'], $updateData);
        }
        catch (\Exception $e)
        {
            Log::write('八字 - 报告【吉日吉时】计算异常 jobData：' . json_encode($jobData, JSON_UNESCAPED_UNICODE) . ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine(), 'error');
            $extend = json_decode($HoroscopeGoodTimeInfo['extend'], true);
            // 计算失败
            $extend['error_msg'] = [
                'msg' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
            ];
            $HoroscopeGoodTimeModel->UpdateData($jobData['id'], ['status' => 3, 'end_time' => time(), 'extend' => json_encode($extend, JSON_UNESCAPED_UNICODE)]);
        }

        $job->delete();
    }
}